﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data;

namespace Providers
{
    public class Contexto : DbContext
    {
        public Contexto()
            : base()
        {
        }

        public Contexto(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
        }

        public override int SaveChanges()
        {
            var deletedEntities = GetDeletedEntities();

            SoftDelete(deletedEntities);

            return base.SaveChanges();
        }

        private List<ISoftDeleteEntity> GetDeletedEntities()
        {
            return GetObjectStateManager()
                .GetObjectStateEntries(EntityState.Deleted)
                .Select(entry => entry.Entity)
                .OfType<ISoftDeleteEntity>()
                .ToList();
        }

        private void SoftDelete(ISoftDeleteEntity entity)
        {
            GetObjectStateManager().ChangeObjectState(entity, EntityState.Modified);
            entity.Deleted = true;
        }

        private void SoftDelete(List<ISoftDeleteEntity> deletedEntities)
        {
            deletedEntities.ForEach(e => SoftDelete(e));
        }

        private ObjectStateManager GetObjectStateManager()
        {
            return ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
        }
    }
}
